package cn.rick.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.rick.constant.Constants;
import cn.rick.entity.SysLogininfor;
import cn.rick.entity.SysUser;
import cn.rick.service.ISysLogininforService;
import cn.rick.service.ISysUserService;
import cn.rick.util.RequestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

/**
 * @author Rick
 * @date 2022-10-14 17:21
 */
@RestController
@RequestMapping(value = "/api")
@Api(value = "登录注销控制", tags = {"登录注销控制"})
public class LoginController {

    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private ISysLogininforService iSysLogininforService;


    /**
     * 登录
     *
     * @param map
     * @param request
     * @return
     */
    @PostMapping(value = "/login")
    @ApiOperation("登录控制")
    public SaResult login(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        SysUser user = JSONObject.parseObject(JSON.toJSONString(map), SysUser.class);
        if (Objects.nonNull(user)) {
            SysLogininfor info = new SysLogininfor();
            info.setUserName(user.getUserName());

            RequestUtil requestUtil = new RequestUtil(request);
            UserAgent userAgent = UserAgentUtil.parse(requestUtil.getUa());
            info.setOs(userAgent.getOs().toString());
            info.setBrowser(userAgent.getBrowser().toString() + " " + userAgent.getVersion());
            info.setIpaddr(String.valueOf(map.get("ipaddr")));
            info.setLoginLocation(String.valueOf(map.get("location")));

            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getUserName, user.getUserName());
            SysUser one = iSysUserService.getOne(queryWrapper);
            if (Objects.nonNull(one)) {
                if ("1".equals(one.getStatus())) {
                    info.setStatus("1");
                    info.setMsg("账户已被停用");
                    iSysLogininforService.save(info);
                    return SaResult.error("账户已被停用");
                } else if (one.getPassword().equals(SaSecureUtil.aesEncrypt(Constants.PASSKEY, user.getPassword()))) {
                    StpUtil.login(one.getUserId());

                    SysUser loginUser = new SysUser();
                    loginUser.setUserId(one.getUserId());
                    loginUser.setLoginDate(LocalDateTime.now());
                    loginUser.setLoginIp(String.valueOf(map.get("ipaddr")));
                    iSysUserService.updateById(loginUser);

                    info.setStatus("0");
                    info.setMsg("登录成功");
                    iSysLogininforService.save(info);
                    return SaResult.data(StpUtil.getTokenInfo());
                } else {
                    info.setStatus("1");
                    info.setMsg("密码错误");
                    iSysLogininforService.save(info);
                    return SaResult.error("密码错误");
                }
            } else {
                info.setStatus("1");
                info.setMsg("登录用户：" + user.getUserName() + " 不存在");
                iSysLogininforService.save(info);
                return SaResult.error("用户名不存在");
            }
        } else {
            return SaResult.error("参数错误，用户参数不存在");
        }
    }

    /**
     * 注销方法
     *
     * @return
     */
    @GetMapping(value = "/logout")
    @ApiOperation("注销方法")
    public SaResult logout() {
        if (StpUtil.isLogin()) {
            StpUtil.logout();
            return SaResult.ok("注销成功");
        } else {
            return SaResult.ok("当前登录已经过期");
        }
    }

}
